"""
股票数据 API 路由
"""
import logging
from datetime import datetime
from typing import List, Optional, Dict, Any
from fastapi import APIRouter, HTTPException, Depends
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
import io

from ..services.stock_service import StockService

router = APIRouter(prefix="/api/stock", tags=["stock"])
logger = logging.getLogger(__name__)

# 依赖注入
async def get_stock_service() -> StockService:
    return StockService()

# 简单的异常处理装饰器
def handle_api_exception(func):
    import functools
    @functools.wraps(func)
    async def wrapper(*args, **kwargs):
        try:
            return await func(*args, **kwargs)
        except HTTPException:
            raise
        except Exception as e:
            logger.error(f"API错误: {str(e)}")
            raise HTTPException(500, f"服务器内部错误: {str(e)}")
    return wrapper


# 请求模型
class StockRequest(BaseModel):
    stock_code: str = "sz.000001"
 
class HistoricalRequest(BaseModel):
    stock_code: str = "sz.000001"
    start_date: Optional[str] = None
    end_date: Optional[str] = None

 
# 简化的响应模型不再需要复杂的类定义，直接返回字典

@router.post("/info", response_model=Dict[str, Any])
@handle_api_exception
async def get_stock_info(
    request: StockRequest,
    service: StockService = Depends(get_stock_service)
):
    """获取单个股票基本信息（包含字段描述）"""
    result = await service.get_stock_info(request.stock_code)
    
    if not result:
        raise HTTPException(404, f"股票 {request.stock_code} 不存在")
    
    return result


@router.post("/data", response_model=Dict[str, Any])
@handle_api_exception
async def get_historical_data(
    request: HistoricalRequest,
    service: StockService = Depends(get_stock_service)
):
    """获取单个股票历史数据（包含字段描述）"""
    # 处理日期范围
    start_date = request.start_date or "2024-01-01"
    end_date = request.end_date or datetime.now().strftime("%Y-%m-%d")
    
    result = await service.get_historical_data(request.stock_code, start_date, end_date)
    
    if not result:
        raise HTTPException(404, f"未找到股票 {request.stock_code} 的历史数据")
    
    return result


@router.get("/health")
async def check_health(service: StockService = Depends(get_stock_service)):
    """检查数据源健康状态"""
    healthy = await service.check_connection()
    return {"healthy": healthy, "status": "可用" if healthy else "不可用"}


@router.get("/fields", response_model=Dict[str, str])
async def get_field_descriptions(service: StockService = Depends(get_stock_service)):
    """获取所有字段的描述信息"""
    return service.get_field_descriptions()



